﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using RoadFlow.Business;
using RoadFlow.Model;
using RoadFlow.Utility;
using System;
using System.Data;
using System.Text;

namespace RoadFlow.Mvc.Areas.RoadFlowCore.Controllers
{
    [Area("RoadFlowCore")]
    public class MailController : Controller
    {
        [Validate(CheckApp = false)]
        public IActionResult SendMail()
        {
            string str1 = this.Request.Querys("opation");
            Mail mail = new Mail();
            MailOutBox mailOutBox = (MailOutBox)null;
            string str2 = string.Empty;
            string str3 = string.Empty;
            string str4 = string.Empty;
            string str5 = string.Empty;
            string str6 = string.Empty;
            bool flag1 = str1.Equals("redirect");
            bool flag2 = str1.Equals("return");
            bool flag3 = str1.Equals("againedit");
            if (flag1 | flag2 | flag3)
            {
                Guid guid;
                if (this.Request.Querys("mailid").IsGuid(out guid))
                {
                    if (flag3)
                    {
                        mailOutBox = mail.GetMailOutBox(guid);
                    }
                    else
                    {
                        MailInBox mailInBox = mail.GetMailInBox(guid);
                        if (mailInBox != null)
                        {
                            mailOutBox = mail.GetMailOutBox(mailInBox.OutBoxId);
                            if (mailOutBox != null)
                            {
                                mailOutBox.ReceiveUsers = flag1 ? "" : "u_" + mailInBox.SendUserId.ToString();
                                mailOutBox.SubjectColor = string.Empty;
                                mailOutBox.Subject = (flag1 ? "转发" : (flag2 ? "回复" : "")) + "：" + mailInBox.Subject;
                            }
                        }
                    }
                }
            }
            else
            {
                Guid guid;
                if (this.Request.Querys("id").IsGuid(out guid))
                    mailOutBox = mail.GetMailOutBox(guid);
            }
            if (mailOutBox != null)
            {
                str4 = mailOutBox.ReceiveUsers;
                str5 = mailOutBox.Subject;
                str6 = mailOutBox.SubjectColor;
                MailContent mailContent = mail.GetMailContent(mailOutBox.ContentsId);
                if (mailContent != null)
                {
                    if (flag1 | flag2)
                        str2 = "<p></p><p>------------------原始邮件------------------</p><p>发件人：" + new RoadFlow.Business.User().GetName(mailOutBox.UserId) + "(" + new RoadFlow.Business.User().GetOrganizeMainShowHtml(mailOutBox.UserId, false) + ")&nbsp;&nbsp;收件时间：" + mailOutBox.SendDateTime.ToShortDateTimeString() + "</p>" + mailContent.Contents;
                    else
                        str2 = mailContent.Contents;
                    str3 = mailContent.Files;
                }
            }
            this.ViewData["contents"] = (object)str2;
            this.ViewData["files"] = (object)str3;
            this.ViewData["receiveUsers"] = (object)str4;
            this.ViewData["subject"] = (object)str5;
            this.ViewData["subjectColor"] = (object)str6;
            this.ViewData["refreshtabid"] = (object)this.Request.Querys("refreshtabid");
            this.ViewData["query"] = (object)("appid=" + this.Request.Querys("appid") + "&rf_appopenmodel=" + this.Request.Querys("rf_appopenmodel") + "&tabid=" + this.Request.Querys("tabid"));
            this.ViewData["queryString"] = (object)this.Request.UrlQuery();
            return (IActionResult)this.View();
        }

        [Validate(CheckApp = false)]
        public IActionResult ShowMail()
        {
            string str1 = this.Request.Querys("mailid");
            MailInBox mailInBox = (MailInBox)null;
            Mail mail = new Mail();
            Guid guid;
            if (str1.IsGuid(out guid))
                mailInBox = mail.GetMailInBox(guid);
            if (mailInBox == null)
                return (IActionResult)new ContentResult()
                {
                    Content = "未找到该邮件!"
                };
            if (mailInBox.IsRead == 0)
                mail.UpdateIsRead(mailInBox.Id, 1, true);
            string str2 = string.Empty;
            string str3 = string.Empty;
            MailContent mailContent = mail.GetMailContent(mailInBox.ContentsId);
            if (mailContent != null)
            {
                str2 = mailContent.Contents;
                str3 = mailContent.Files.ToFilesShowString(false);
            }
            this.ViewData["contents"] = (object)str2;
            this.ViewData["files"] = (object)str3;
            this.ViewData["mailid"] = (object)mailInBox.Id;
            this.ViewData["query"] = (object)("appid=" + this.Request.Querys("appid") + "&rf_appopenmodel=" + this.Request.Querys("rf_appopenmodel") + "&tabid=" + this.Request.Querys("tabid") + "&pagesize=" + this.Request.Querys("pagesize") + "&pagenumber=" + this.Request.Querys("pagenumber"));
            return (IActionResult)this.View((object)mailInBox);
        }

        [Validate(CheckApp = false)]
        public string SaveSendMail()
        {
            string str1 = this.Request.Forms("ReceiveUsers");
            string str2 = this.Request.Forms("Subject");
            string str3 = this.Request.Forms("SubjectColor");
            string str4 = this.Request.Forms("Contents");
            string str5 = this.Request.Forms("Files");
            string str6 = this.Request.Querys("id");
            int num = this.Request.Forms("Status").ToInt(0);
            if (str2.IsNullOrWhiteSpace() || str4.IsNullOrWhiteSpace() || num == 1 && str1.IsNullOrWhiteSpace())
                return "{\"success\":0,\"message\":\"数据验证错误!\"}";
            Mail mail = new Mail();
            MailOutBox mailOutBox = (MailOutBox)null;
            bool isAdd = false;
            Guid guid;
            if (str6.IsGuid(out guid))
                mailOutBox = mail.GetMailOutBox(guid);
            if (mailOutBox == null)
            {
                isAdd = true;
                mailOutBox = new MailOutBox()
                {
                    Id = Guid.NewGuid(),
                    ContentsId = Guid.NewGuid()
                };
            }
            MailContent mailContent = new MailContent()
            {
                Id = mailOutBox.ContentsId
            };
            mailContent.Contents = str4;
            mailContent.Files = str5;
            mailOutBox.ReceiveUsers = str1;
            mailOutBox.SendDateTime = DateExtensions.Now;
            mailOutBox.Status = num;
            mailOutBox.Subject = str2.Trim();
            if (!str3.IsNullOrWhiteSpace())
                mailOutBox.SubjectColor = str3;
            mailOutBox.UserId = Current.UserId;
            mail.Send(mailOutBox, mailContent, isAdd);
            return "{\"success\":1,\"message\":\"" + (num == 0 ? "保存" : "发送") + "成功!\",\"id\":\"" + (num == 0 ? mailOutBox.Id.ToString() : "") + "\"}";
        }

        [Validate(CheckApp = false)]
        public string ChangeStatus()
        {
            Mail mail = new Mail();
            foreach (string str in this.Request.Forms("ids").Split(',', StringSplitOptions.None))
            {
                Guid guid;
                if (str.IsGuid(out guid))
                {
                    MailInBox mailInBox = mail.GetMailInBox(guid);
                    if (mailInBox != null && mailInBox.IsRead != 1)
                        mail.UpdateIsRead(guid, 1, true);
                }
            }
            return "标记成功!";
        }

        [Validate(CheckApp = false)]
        [ValidateAntiForgeryToken]
        public string DeleteMail()
        {
            Guid guid;
            if (!this.Request.Forms("mailid").IsGuid(out guid))
                return "邮件Id错误!";
            int status = this.Request.Forms("status").ToInt(0);
            new Mail().DeleteMailInBox(guid, status);
            return (1 == status ? "彻底" : "") + "删除成功!";
        }

        [Validate(CheckApp = false)]
        public string DeleteMail1()
        {
            Mail mail = new Mail();
            foreach (string str in this.Request.Forms("ids").Split(',', StringSplitOptions.None))
            {
                Guid guid;
                if (str.IsGuid(out guid))
                    mail.DeleteMailInBox(guid, 0);
            }
            return "删除成功!";
        }

        [Validate(CheckApp = false)]
        public IActionResult InBox()
        {
            this.ViewData["appId"] = (object)this.Request.Querys("appid");
            this.ViewData["tabId"] = (object)this.Request.Querys("tabid");
            this.ViewData["query"] = (object)("appid=" + this.Request.Querys("appid") + "&rf_appopenmodel=" + this.Request.Querys("rf_appopenmodel"));
            return (IActionResult)this.View();
        }

        [Validate(CheckApp = false)]
        public string QueryInBox()
        {
            string str1 = this.Request.Forms("sidx");
            string str2 = this.Request.Forms("sord");
            string subject = this.Request.Forms("Subject");
            string str3 = this.Request.Forms("SendUser");
            string date1 = this.Request.Forms("Date1");
            string date2 = this.Request.Forms("Date2");
            int pageSize = Tools.GetPageSize(true);
            int pageNumber = Tools.GetPageNumber();
            string order = (str1.IsNullOrEmpty() ? "SendDateTime" : str1) + " " + (str2.IsNullOrEmpty() ? "DESC" : str2);
            int count;
            DataTable mailInBoxPagerList = new Mail().GetMailInBoxPagerList(out count, pageSize, pageNumber, Current.UserId, subject, str3.IsNullOrWhiteSpace() ? "" : str3.RemoveUserRelationPrefix(), date1, date2, order);
            JArray jarray = new JArray();
            RoadFlow.Business.User user = new RoadFlow.Business.User();
            RoadFlow.Business.Organize organize = new RoadFlow.Business.Organize();
            foreach (DataRow row in (InternalDataCollectionBase)mailInBoxPagerList.Rows)
            {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("<a href=\"javascript:;\" class=\"blue\" onclick=\"detail('" + row["Id"].ToString() + "');\">");
                if (row["SubjectColor"].ToString().IsNullOrWhiteSpace())
                    stringBuilder.Append(row["Subject"].ToString());
                else
                    stringBuilder.Append("<span style=\"color:" + row["SubjectColor"].ToString() + "\">" + row["Subject"].ToString() + "</span>");
                stringBuilder.Append("</a>");
                JObject jobject = new JObject()
        {
          {
            "id",
            (JToken) row["Id"].ToString()
          },
          {
            "Subject",
            (JToken) stringBuilder.ToString()
          },
          {
            "SendDateTime",
            (JToken) row["SendDateTime"].ToString().ToDateTime().ToDateTimeString()
          },
          {
            "SendUserId",
            (JToken) (user.GetName(row["SendUserId"].ToString().ToGuid()) + "<span style=\"color:#666;margin-left:5px;\">(" + user.GetOrganizeMainShowHtml(row["SendUserId"].ToString().ToGuid(), false) + ")</span>")
          },
          {
            "IsRead",
            (JToken) (row["IsRead"].ToString().Equals("0") ? "<span class=\"noread\">未读</span>" : "<span class=\"read\">已读</span>")
          }
        };
                jarray.Add((JToken)jobject);
            }
            return "{\"userdata\":{\"total\":" + (object)count + ",\"pagesize\":" + (object)pageSize + ",\"pagenumber\":" + (object)pageNumber + "},\"rows\":" + jarray.ToString() + "}";
        }

        [Validate(CheckApp = false)]
        public IActionResult DraftBox()
        {
            this.ViewData["appId"] = (object)this.Request.Querys("appid");
            this.ViewData["tabId"] = (object)this.Request.Querys("tabid");
            this.ViewData["query"] = (object)("appid=" + this.Request.Querys("appid") + "&rf_appopenmodel=" + this.Request.Querys("rf_appopenmodel"));
            return (IActionResult)this.View();
        }

        [Validate(CheckApp = false)]
        public string QueryDraftBox()
        {
            string str1 = this.Request.Forms("sidx");
            string str2 = this.Request.Forms("sord");
            string subject = this.Request.Forms("Subject");
            string date1 = this.Request.Forms("Date1");
            string date2 = this.Request.Forms("Date2");
            int pageSize = Tools.GetPageSize(true);
            int pageNumber = Tools.GetPageNumber();
            string order = (str1.IsNullOrEmpty() ? "SendDateTime" : str1) + " " + (str2.IsNullOrEmpty() ? "DESC" : str2);
            int count;
            DataTable mailOutBoxPagerList = new Mail().GetMailOutBoxPagerList(out count, pageSize, pageNumber, Current.UserId, subject, date1, date2, order, 0);
            JArray jarray = new JArray();
            RoadFlow.Business.User user = new RoadFlow.Business.User();
            RoadFlow.Business.Organize organize = new RoadFlow.Business.Organize();
            foreach (DataRow row in (InternalDataCollectionBase)mailOutBoxPagerList.Rows)
            {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("<a href=\"javascript:;\" class=\"blue\" onclick=\"detail('" + row["Id"].ToString() + "');\">");
                if (row["SubjectColor"].ToString().IsNullOrWhiteSpace())
                    stringBuilder.Append(row["Subject"].ToString());
                else
                    stringBuilder.Append("<span style=\"color:" + row["SubjectColor"].ToString() + "\">" + row["Subject"].ToString() + "</span>");
                stringBuilder.Append("</a>");
                JObject jobject = new JObject()
        {
          {
            "id",
            (JToken) row["Id"].ToString()
          },
          {
            "Subject",
            (JToken) stringBuilder.ToString()
          },
          {
            "SendDateTime",
            (JToken) row["SendDateTime"].ToString().ToDateTime().ToDateTimeString()
          }
        };
                jarray.Add((JToken)jobject);
            }
            return "{\"userdata\":{\"total\":" + (object)count + ",\"pagesize\":" + (object)pageSize + ",\"pagenumber\":" + (object)pageNumber + "},\"rows\":" + jarray.ToString() + "}";
        }

        [Validate(CheckApp = false)]
        public string DeleteDraftMail()
        {
            Mail mail = new Mail();
            foreach (string str in this.Request.Forms("ids").Split(',', StringSplitOptions.None))
            {
                Guid guid;
                if (str.IsGuid(out guid))
                    mail.DeleteMailOutBox(guid);
            }
            return "删除成功!";
        }

        [Validate(CheckApp = false)]
        public IActionResult OutBox()
        {
            this.ViewData["appId"] = (object)this.Request.Querys("appid");
            this.ViewData["tabId"] = (object)this.Request.Querys("tabid");
            this.ViewData["query"] = (object)("appid=" + this.Request.Querys("appid") + "&rf_appopenmodel=" + this.Request.Querys("rf_appopenmodel"));
            return (IActionResult)this.View();
        }

        [Validate(CheckApp = false)]
        public string QueryOutBox()
        {
            string str1 = this.Request.Forms("sidx");
            string str2 = this.Request.Forms("sord");
            string subject = this.Request.Forms("Subject");
            string date1 = this.Request.Forms("Date1");
            string date2 = this.Request.Forms("Date2");
            int pageSize = Tools.GetPageSize(true);
            int pageNumber = Tools.GetPageNumber();
            string order = (str1.IsNullOrEmpty() ? "SendDateTime" : str1) + " " + (str2.IsNullOrEmpty() ? "DESC" : str2);
            int count;
            DataTable mailOutBoxPagerList = new Mail().GetMailOutBoxPagerList(out count, pageSize, pageNumber, Current.UserId, subject, date1, date2, order, 1);
            JArray jarray = new JArray();
            RoadFlow.Business.User user = new RoadFlow.Business.User();
            RoadFlow.Business.Organize organize = new RoadFlow.Business.Organize();
            foreach (DataRow row in (InternalDataCollectionBase)mailOutBoxPagerList.Rows)
            {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("<a href=\"javascript:;\" class=\"blue\" onclick=\"detail('" + row["Id"].ToString() + "');\">");
                if (row["SubjectColor"].ToString().IsNullOrWhiteSpace())
                    stringBuilder.Append(row["Subject"].ToString());
                else
                    stringBuilder.Append("<span style=\"color:" + row["SubjectColor"].ToString() + "\">" + row["Subject"].ToString() + "</span>");
                stringBuilder.Append("</a>");
                JObject jobject = new JObject()
        {
          {
            "id",
            (JToken) row["Id"].ToString()
          },
          {
            "Subject",
            (JToken) stringBuilder.ToString()
          },
          {
            "SendDateTime",
            (JToken) row["SendDateTime"].ToString().ToDateTime().ToDateTimeString()
          }
        };
                jarray.Add((JToken)jobject);
            }
            return "{\"userdata\":{\"total\":" + (object)count + ",\"pagesize\":" + (object)pageSize + ",\"pagenumber\":" + (object)pageNumber + "},\"rows\":" + jarray.ToString() + "}";
        }

        [Validate(CheckApp = false)]
        public string DeleteOutMail()
        {
            Mail mail = new Mail();
            foreach (string str in this.Request.Forms("ids").Split(',', StringSplitOptions.None))
            {
                Guid guid;
                if (str.IsGuid(out guid))
                    mail.DeleteMailOutBox(guid);
            }
            return "删除成功!";
        }

        [Validate(CheckApp = false)]
        public IActionResult ShowOutMail()
        {
            string str1 = this.Request.Querys("mailid");
            MailOutBox mailOutBox = (MailOutBox)null;
            Mail mail = new Mail();
            Guid guid;
            if (str1.IsGuid(out guid))
                mailOutBox = mail.GetMailOutBox(guid);
            if (mailOutBox == null)
                return (IActionResult)new ContentResult()
                {
                    Content = "未找到该邮件!"
                };
            string str2 = string.Empty;
            string str3 = string.Empty;
            MailContent mailContent = mail.GetMailContent(mailOutBox.ContentsId);
            if (mailContent != null)
            {
                str2 = mailContent.Contents;
                str3 = mailContent.Files.ToFilesShowString(false);
            }
            this.ViewData["contents"] = (object)str2;
            this.ViewData["files"] = (object)str3;
            this.ViewData["mailid"] = (object)mailOutBox.Id;
            this.ViewData["query"] = (object)("appid=" + this.Request.Querys("appid"));
            this.ViewData["query1"] = (object)("appid=" + this.Request.Querys("appid") + "&rf_appopenmodel=" + this.Request.Querys("rf_appopenmodel") + "&pagesize=" + this.Request.Querys("pagesize") + "&pagenumber=" + this.Request.Querys("pagenumber"));
            this.ViewData["refreshtabid"] = (object)this.Request.Querys("refreshtabid");
            this.ViewData["isWithdraw"] = (object)mail.IsWithdraw(guid);
            return (IActionResult)this.View((object)mailOutBox);
        }

        [Validate(CheckApp = false)]
        public string WithdrawOutMail()
        {
            Guid guid;
            if (!this.Request.Forms("id").IsGuid(out guid))
                return "邮件ID错误!";
            return new Mail().Withdraw(guid) ? "邮件已成功撤回至草稿箱!" : "撤回失败!";
        }

        [Validate(CheckApp = false)]
        public IActionResult DeletedBox()
        {
            this.ViewData["appId"] = (object)this.Request.Querys("appid");
            this.ViewData["tabId"] = (object)this.Request.Querys("tabid");
            this.ViewData["query"] = (object)("appid=" + this.Request.Querys("appid") + "&rf_appopenmodel=" + this.Request.Querys("rf_appopenmodel"));
            return (IActionResult)this.View();
        }

        [Validate(CheckApp = false)]
        public string QueryDeletedBox()
        {
            string str1 = this.Request.Forms("sidx");
            string str2 = this.Request.Forms("sord");
            string subject = this.Request.Forms("Subject");
            string str3 = this.Request.Forms("SendUser");
            string date1 = this.Request.Forms("Date1");
            string date2 = this.Request.Forms("Date2");
            int pageSize = Tools.GetPageSize(true);
            int pageNumber = Tools.GetPageNumber();
            string order = (str1.IsNullOrEmpty() ? "SendDateTime" : str1) + " " + (str2.IsNullOrEmpty() ? "DESC" : str2);
            int count;
            DataTable deletedBoxPagerList = new Mail().GetMailDeletedBoxPagerList(out count, pageSize, pageNumber, Current.UserId, subject, str3.IsNullOrWhiteSpace() ? "" : str3.RemoveUserRelationPrefix(), date1, date2, order);
            JArray jarray = new JArray();
            RoadFlow.Business.User user = new RoadFlow.Business.User();
            RoadFlow.Business.Organize organize = new RoadFlow.Business.Organize();
            foreach (DataRow row in (InternalDataCollectionBase)deletedBoxPagerList.Rows)
            {
                StringBuilder stringBuilder = new StringBuilder();
                if (row["SubjectColor"].ToString().IsNullOrWhiteSpace())
                    stringBuilder.Append(row["Subject"].ToString());
                else
                    stringBuilder.Append("<span style=\"color:" + row["SubjectColor"].ToString() + "\">" + row["Subject"].ToString() + "</span>");
                JObject jobject = new JObject()
        {
          {
            "id",
            (JToken) row["Id"].ToString()
          },
          {
            "Subject",
            (JToken) stringBuilder.ToString()
          },
          {
            "SendUserId",
            (JToken) (user.GetName(row["SendUserId"].ToString().ToGuid()) + "<span style=\"color:#666;margin-left:5px;\">(" + user.GetOrganizeMainShowHtml(row["SendUserId"].ToString().ToGuid(), false) + ")</span>")
          },
          {
            "SendDateTime",
            (JToken) row["SendDateTime"].ToString().ToDateTime().ToDateTimeString()
          }
        };
                jarray.Add((JToken)jobject);
            }
            return "{\"userdata\":{\"total\":" + (object)count + ",\"pagesize\":" + (object)pageSize + ",\"pagenumber\":" + (object)pageNumber + "},\"rows\":" + jarray.ToString() + "}";
        }

        [Validate(CheckApp = false)]
        public string Recovery()
        {
            string str1 = this.Request.Forms("ids");
            Mail mail = new Mail();
            foreach (string str2 in str1.Split(',', StringSplitOptions.None))
            {
                Guid guid;
                if (str2.IsGuid(out guid))
                    mail.RecoveryMailDeletedBox(guid);
            }
            return "邮件已成功还原至收件箱!";
        }

        [Validate(CheckApp = false)]
        public string DeleteDeletedMail()
        {
            Mail mail = new Mail();
            foreach (string str in this.Request.Forms("ids").Split(',', StringSplitOptions.None))
            {
                Guid guid;
                if (str.IsGuid(out guid))
                {
                    MailDeletedBox mailDeletedBox = mail.GetMailDeletedBox(guid);
                    if (mailDeletedBox != null)
                        mail.DeleteMailDeletedBox(mailDeletedBox);
                }
            }
            return "删除成功!";
        }
    }
}
